<?php

final class ConstructQueries {
    private static $getLayout = 'SELECT `id`, `title`, `link`, `contents`, `parcels`
                                 FROM `layouts`
                                 WHERE `link` = ?';

	private static $readSession = 'SELECT data FROM %s
								   WHERE name = ? AND id = ? LIMIT 1';

	private static $writeSession = 'INSERT INTO %s (id, name, time, data)
									 VALUES(?, ?, ?, ?)
									 ON DUPLICATE KEY UPDATE
									 data = VALUES(data), time = VALUES(time)';

	private static $destroySession = 'DELETE FROM %s
									  WHERE id = ? AND name = ? LIMIT 1';

	private static $garbageCollectSessions = 'DELETE FROM %s WHERE time < ?';
    
    private function __construct() {} // So the class can't be instantiated.
    
    public static function GetLayout(Registry $registry, $page) {
        $DB = $registry->Get('DB');

        $query = new pQuery(self::$getLayout);

        $DB->Query($query);
        $query->SetParams($page);
        return $query->FetchResult();
    }

	public static function ReadSession(Registry $registry, $tableName, $id, $name) {
		$DB = $registry->Get('DB');

		$query = new pQuery(sprintf(self::$readSession, $tableName));

		$DB->Query($query, false);
		$query->SetParams($id, $name);
		return $query->FetchResult();
	}

	public static function WriteSession(Registry $registry, $tableName, $id, $name, $time, $data) {
		$DB = $registry->Get('DB');

		$query = new pQuery(sprintf(self::$writeSession, $tableName));

		$DB->Query($query, false);
		$query->SetParams($id, $name, $time, $data);
		// We need to fetch results even though it is a query that does not
		// return anything because it also closes the cursor.
		return true;
	}

	public static function DestroySession(Registry $registry, $tableName, $id, $name) {
		$DB = $registry->Get('DB');

		$query = new pQuery(sprintf(self::$destroySession, $tableName));

		$DB->Query($query, false);
		$query->SetParams($id, $name);
		// We need to fetch results even though it is a query that does not
		// return anything because it also closes the cursor.
		$query->FetchResult();
		return true;
	}

	public static function GarbageCollectSessions(Registry $registry, $tableName, $time) {
		$DB = $registry->Get('DB');

		$query = new pQuery(sprintf(self::$garbageCollectSessions, $tableName));

		$DB->Query($query, false);
		$query->SetParams($time);
		// We need to fetch results even though it is a query that does not
		// return anything because it also closes the cursor.
		$query->FetchResult();
		return true;
	}

}